﻿Imports System.Security.Cryptography
Imports System.Text
Imports DTO
Imports BUS

Public Class FormDoiMKTaiKhoan

    Dim _taiKhoanBUS As New TaiKhoanBUS
    Public _flag As Integer = 0
    Public _tenDN As String
    Private Sub btnXacNhan_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnXacNhan.Click
        If (KiemTraInput()) Then
            _flag = 1
            Dim _tkDTO As New TaiKhoanDTO(_tenDN, getMd5Hash(txtMKMoi.Text), Nothing)
            _taiKhoanBUS.DoiMKBUS(_tkDTO)
            MessageBox.Show("Bạn đã thay đổi MK thành công")
            Me.Close()
        End If
    End Sub
    Public Function KiemTraInput() As Boolean
        If (txtMKCu.Text = "" Or txtMKMoi.Text = "" Or txtXacNhanMKMoi.Text = "") Then
            MessageBox.Show("Mời bạn điền đấy đủ thông tin", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Return False
        End If

        Dim _mkCu As String = getMd5Hash(txtMKCu.Text)
        Dim _mkMoi As String = getMd5Hash(txtMKMoi.Text)
        Dim _mkXacNhan As String = getMd5Hash(txtXacNhanMKMoi.Text)

        Dim _taiKhoanDTO As New TaiKhoanDTO(_tenDN, _mkCu, Nothing)


        If (_taiKhoanBUS.KiemTraTKVaMKDAO(_taiKhoanDTO) = False) Then
            MessageBox.Show("Kiểm tra lại mật khẩu cũ", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Return False
        End If

        If (_mkMoi <> _mkXacNhan) Then
            MessageBox.Show("Mật khẩu xác nhận phải trùng với mật khẩu mới", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Return False
        End If
        Return True
    End Function
    Function getMd5Hash(ByVal input As String) As String
        ' Create a new instance of the MD5 object.
        Dim md5Hasher As MD5 = MD5.Create()

        ' Convert the input string to a byte array and compute the hash.
        Dim data As Byte() = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input))

        ' Create a new Stringbuilder to collect the bytes
        ' and create a string.
        Dim sBuilder As New StringBuilder()

        ' Loop through each byte of the hashed data 
        ' and format each one as a hexadecimal string.
        Dim i As Integer
        For i = 0 To data.Length - 1
            sBuilder.Append(data(i).ToString("x2"))
        Next i

        ' Return the hexadecimal string.
        Return sBuilder.ToString()

    End Function

    Private Sub btnHuy_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnHuy.Click
        Me.Close()
    End Sub
End Class